package cn.com.shaom.learning.sb.shiro.example.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * ClassName: ShiroConfig
 * Description:
 * Date: 2018/2/22 10:23 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Configuration
public class ShiroConfig {


    @Bean
    public Realm realm() {
        CustomRealm customRealm = new CustomRealm();
//        customRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return customRealm;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //散列算法:这里使用MD5算法;
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        //散列的次数，比如散列两次，相当于 md5(md5(""));
        hashedCredentialsMatcher.setHashIterations(2);
        return hashedCredentialsMatcher;
    }

    /**
     * @param securityManager
     * @return
     */
    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 默认是 "/login.jsp"
        shiroFilterFactoryBean.setLoginUrl("/login");
        // 默认是 "/",这个配置是附加配置，详见 [https://www.cnblogs.com/yeming/p/5480639.html]
        // successUrl配置只是做为一种附加配置，只有session中没有用户请求地址时才会使用successUrl。
        // 系统默认的是认证成功后跳转到上一次请求的路径，如果是首次请求，那 shiro 就会跳转到默认虚拟路径 "/"
        // 可以自定义 FormAuthenticationFilter
        shiroFilterFactoryBean.setSuccessUrl("/hello");
        //未授权界面;
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");

        // authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问
        Map<String, String> map = new LinkedHashMap<>();
        // 配置不会被拦截的链接 顺序判断
        map.put("/css/**", "anon");
        map.put("/fonts/**", "anon");
        map.put("/js/**", "anon");

        // 配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
        map.put("/logout", "logout");

        map.put("/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }
}
